﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using System.Web.Security;
using IronOne.SalesOne.BusinessObjects;
using Facade;
using System.Collections;
using IronOne.SalesOne.DataObjects;


namespace IronOne.SalesOne.SalesOneWeb
{
    public partial class AddUser : SOSecurityPage
    {
        User usr;
        private string action = "create";
        private int userId;

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (wizCreateUser.ActiveStepIndex == 2)
                {
                    if (true)
                    {
                        if (Session["gr"] != null)
                        {
                            Session.Remove("gr");
                        }

                        if (Session["br"] != null)
                        {
                            Session.Remove("br");
                        }

                        if (Session["un"] != null)
                        {
                            Session.Remove("un");
                        }


                    }

                }

                if (rdoUserTypes.SelectedIndex != -1)
                {
                    if (rdoUserTypes.SelectedIndex == 0)
                    {//hq

                    }
                    else if (rdoUserTypes.SelectedIndex == 1)
                    {//gr
                        reqNode.ControlToValidate = "drpGroup";
                    }
                    else if (rdoUserTypes.SelectedIndex == 2)
                    {//br
                        reqNode.ControlToValidate = "drpBranch";
                    }
                    else if (rdoUserTypes.SelectedIndex == 3)
                    {//un
                        reqNode.ControlToValidate = "drpUnit";
                    }
                }


                if (!Page.IsPostBack)
                {
                    ValidateUserCredentials(Request.Url.LocalPath);


                    if (!string.IsNullOrEmpty(Request.UrlReferrer.ToString()))
                    {
                        ViewState["refUrl"] = Request.UrlReferrer.ToString();
                    }

                    if (action == "create")
                    {


                        //lblHeader.Text = "Create new user account";

                        DropDownList idType = (DropDownList)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("drpIdType");
                        CodeFacade coFac = new CodeFacade();
                        List<IDType> id = coFac.GetIDTypes("CodeId ASC");
                        IDType idSel = new IDType();

                        idSel.CodeId = -1;
                        idSel.Description = "Select";
                        id.Insert(0, idSel);

                        idType.DataSource = id;
                        idType.DataTextField = "Description";
                        idType.DataValueField = "CodeId";
                        idType.DataBind();

                        DropDownList country = (DropDownList)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("drpCountry");
                        List<Country> coun = coFac.GetCountries("CodeId ASC");
                        Country cSel = new Country();
                        cSel.CodeId = -1;
                        cSel.Description = "Select";
                        coun.Insert(0, cSel);

                        country.DataSource = coun;
                        country.DataTextField = "Description";
                        country.DataValueField = "CodeId";
                        country.DataBind();

                        country.Items.FindByText("Sri Lanka").Selected = true;

                    }
                }



                if (!String.IsNullOrEmpty(Request.QueryString["a"]))
                {
                    action = Request.QueryString["a"].ToString();

                }
            }
            catch (Exception)
            {

            }

            

        }

        private void Update()
        {


        }


        protected void On_Activate(object sender, EventArgs e)
        {
            try
            {
                StructureFacade st = new StructureFacade();
                List<UserType> userTypes = st.GetUserTypes("UserTypeId ASC");


                string usrType = "EMPTY";

                if (!String.IsNullOrEmpty(Request.QueryString["x"]))
                {
                    usrType = Request.QueryString["x"].ToString();

                }


                rdoUserTypes.DataSource = userTypes;
                rdoUserTypes.DataTextField = "UserTypeName";
                rdoUserTypes.DataValueField = "UserTypeId";
                rdoUserTypes.DataBind();


                chkUserType.DataSource = userTypes;
                chkUserType.DataTextField = "UserTypeName";
                chkUserType.DataValueField = "UserTypeId";
                chkUserType.DataBind();

                switch (usrType)
                {
                    case "HQ":
                        FillDropDown("Group");
                        rdoUserTypes.Items[0].Selected = true;
                        rdoUserTypes.Enabled = false;
                        break;
                    case "group":
                        FillDropDown("Group");
                        rdoUserTypes.Items[1].Selected = true;
                        rdoUserTypes.Enabled = false;
                        break;
                    case "b":
                        FillDropDown("Group");
                        rdoUserTypes.Items[2].Selected = true;
                        rdoUserTypes.Enabled = false;
                        break;
                    case "u":
                        FillDropDown("Group");
                        rdoUserTypes.Items[3].Selected = true;
                        rdoUserTypes.Enabled = false;
                        break;
                    default:
                        break;
                }
            }
            catch (Exception)
            {

            }

        }

        protected void On_Deactivate(object sender, EventArgs e)
        {
            
        }


        //bak
        //using (TransactionScope txScope = new TransactionScope())
        //        {
                
        //            StructureFacade stFac = new StructureFacade();

        //            if (chkRoles.Items.Count == 0)
        //            {
        //                wizCreateUser.ActiveStepIndex = 1;
        //                MassageSummery("IIS502");
        //                //lblError.Text = lblError.Text + " Please select at least 1 role.";
        //                return;

        //            }
        //            else
        //            {
                        
        //                //create the user
        //                MembershipCreateStatus status;
        //                //string[] usrProps = { name.Text, idType.SelectedValue.ToString(), idNo.Text, address1.Text, address2.Text, country.Text, city.Text, gender.Text, contact.Text, postalCode.Text, userName.Text, passWord.Text, eMail.Text, question.Text, answer.Text };
        //                string[] usrProps = (string[])Session["newUser"];
        //                MembershipUser newUs = Membership.CreateUser(usrProps[10], usrProps[11], usrProps[12], usrProps[13], usrProps[14], true, out status);

        //                if (newUs == null)
        //                {
        //                    switch (status)
        //                    {
        //                        case MembershipCreateStatus.DuplicateUserName:
        //                            throw new Exception("Username already exists. Please enter a different user name.");
        //                            break;
        //                        case MembershipCreateStatus.DuplicateEmail:
        //                            throw new Exception("A username for that e-mail address already exists. Please enter a different e-mail address.");
        //                            break;
        //                        case MembershipCreateStatus.InvalidPassword:
        //                            throw new Exception("The password provided is invalid. Please enter a valid password value.");
        //                            break;
        //                        case MembershipCreateStatus.InvalidEmail:
        //                            throw new Exception("The e-mail address provided is invalid. Please check the value and try again.");
        //                            break;
        //                        case MembershipCreateStatus.InvalidAnswer:
        //                            throw new Exception("The password retrieval answer provided is invalid. Please check the value and try again.");
        //                            break;
        //                        case MembershipCreateStatus.InvalidQuestion:
        //                            throw new Exception("The password retrieval question provided is invalid. Please check the value and try again.");
        //                            break;
        //                        case MembershipCreateStatus.InvalidUserName:
        //                            throw new Exception("The user name provided is invalid. Please check the value and try again.");
        //                            break;
        //                        case MembershipCreateStatus.ProviderError:
        //                            throw new Exception("The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.");
        //                            break;
        //                        case MembershipCreateStatus.UserRejected:
        //                            throw new Exception("The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.");
        //                            break;
        //                        default:
        //                            throw new Exception("An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.");

        //                    }
        //                }




        //                MembershipUser usr = Membership.GetUser(usrProps[10]);
        //                Guid userGuuid = (Guid)usr.ProviderUserKey;
        //                User user = new User();


        //                MembershipUser adUser = Membership.GetUser(User.Identity.Name);
        //                Guid adkey = (Guid)adUser.ProviderUserKey;

        //                user.LastUpBy = adkey;
        //                user.UserId = userGuuid;
        //                user.Name = usrProps[0];
        //                if (usrProps[1] != "-1")
        //                {
        //                    user.IdType = usrProps[1];
        //                }

        //                user.IdNo = usrProps[2];
        //                user.Address1 = usrProps[3];
        //                user.Address2 = usrProps[4];

        //                if (usrProps[5] != "-1")
        //                {
        //                    user.Country = usrProps[5];
        //                }

        //                user.City = usrProps[6];
        //                user.Gender = Convert.ToByte(usrProps[7]);
        //                user.Contact = usrProps[8];
        //                if (!string.IsNullOrEmpty(usrProps[9]))
        //                {
        //                    user.PostalCode = Convert.ToInt32(usrProps[9]);
        //                }

        //                user.LastUpdateDate = DateTime.Now;

        //                StructureFacade StructureFacade = new StructureFacade();

        //                StructureFacade.InsertUser(user);
                    


        //                string[] usrProp = (string[])Session["newUser"];

        //                string[] roleName;

        //                for (int i = 0; i < chkRoles.Items.Count - 1; i++)
        //                {
        //                    if (chkRoles.Items[i].Selected)
        //                    {

        //                        Roles.AddUserToRole(usrProp[10], chkRoles.Items[i].Text);

        //                    }
        //                }
        //            }

                    

        //            MembershipUser usrs = Membership.GetUser(wizCreateUser.UserName);
        //            Guid userGuuids = (Guid)usrs.ProviderUserKey;

        //            short userType = (short)Convert.ToInt32(rdoUserTypes.SelectedValue);

        //            int nodeId = 0;

        //            if (rdoUserTypes.SelectedItem.Text == "Group" && drpGroup.SelectedValue != "-1")
        //            {
        //                nodeId = Convert.ToInt32(drpGroup.SelectedValue);
        //                stFac.InsertToUserInStructure(userGuuids, userType, nodeId);
        //            }
        //            else if (rdoUserTypes.SelectedItem.Text == "Branch" && drpBranch.SelectedValue != "-1")
        //            {
        //                nodeId = Convert.ToInt32(drpBranch.SelectedValue);
        //                stFac.InsertToUserInStructure(userGuuids, userType, nodeId);
        //            }
        //            else if (rdoUserTypes.SelectedItem.Text == "Unit" && drpUnit.SelectedValue != "-1")
        //            {
        //                nodeId = Convert.ToInt32(drpUnit.SelectedValue);
        //                stFac.InsertToUserInStructure(userGuuids, userType, nodeId);
        //            }
        //            else if (rdoUserTypes.SelectedItem.Text == "HQ")
        //            {
        //                stFac.InsertToUserInStructure(userGuuids, userType, nodeId);
        //            }
        //            else
        //            {
        //                lblError.Text = "Please select a valid unit.";
        //                wizCreateUser.ActiveStepIndex = 1;
        //            }



        //            txScope.Complete();
        //            }
             

        //

        private void addToRoles(string userName, string[] roles)
        {
            try
            {
                Roles.AddUserToRoles(userName, roles);
            }
            catch (Exception)
            {

            }
            
        }


        protected void wizCreateUser_CreatedUser(object sender, EventArgs e)
        {

        }

        protected void wizCreateUser_CreatedUser1(object sender, EventArgs e)
        {
            try
            {
                if (!String.IsNullOrEmpty(Request.QueryString["a"]))
                {
                    action = Request.QueryString["a"].ToString();


                }

                if (action == "v")
                {
                    Response.Redirect(Request.UrlReferrer.ToString());
                }
                else
                {
                    TextBox name = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("txtName");
                    DropDownList idType = (DropDownList)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("drpIdType");
                    TextBox idNo = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("txtIdNo");
                    TextBox address1 = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("txtAddress1");
                    TextBox address2 = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("txtAddress2");
                    DropDownList country = (DropDownList)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("drpCountry");
                    TextBox city = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("txtCity");
                    DropDownList gender = (DropDownList)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("drpGender");
                    TextBox contact = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("txtContact");
                    TextBox postalCode = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("txtPostalCode");

                    TextBox userName = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("UserName");

                    MembershipUser usr = Membership.GetUser(userName.Text);
                    Guid userGuuid = (Guid)usr.ProviderUserKey;
                    User user = new User();




                    MembershipUser adUser = Membership.GetUser(User.Identity.Name);
                    Guid adkey = (Guid)adUser.ProviderUserKey;

                    user.LastUpBy = adkey.ToString();
                    user.UserId = userGuuid;
                    user.Name = name.Text;
                    if (idType.SelectedValue != "-1")
                    {
                        user.IdType = idType.SelectedValue;
                    }

                    user.IdNo = idNo.Text;
                    user.Address1 = address1.Text;
                    user.Address2 = address2.Text;

                    if (country.SelectedValue != "-1")
                    {
                        user.Country = country.SelectedValue;
                    }

                    user.City = city.Text;
                    user.Gender = gender.SelectedValue;
                    user.Contact = contact.Text;
                    user.PostalCode = postalCode.Text;

                    //if (!string.IsNullOrEmpty(postalCode.Text))
                    //{
                    //    user.PostalCode = Convert.ToInt32(postalCode.Text);
                    //}


                    user.LastUpdateDate = DateTime.Now.ToShortDateString();



                    StructureFacade StructureFacade = new StructureFacade();

                    StructureFacade.InsertUser(user);


                    //Context.Profile.SetPropertyValue("Name", name.Text);
                    //Context.Profile.SetPropertyValue("IdType", idType.SelectedValue);
                    //Context.Profile.SetPropertyValue("IdNo", idNo.Text);
                    //Context.Profile.SetPropertyValue("Address1", address1.Text);
                    //Context.Profile.SetPropertyValue("Address2", address2.Text);
                    //Context.Profile.SetPropertyValue("Country", country.SelectedValue);
                    //Context.Profile.SetPropertyValue("City", city.Text);
                    //Context.Profile.SetPropertyValue("Gender", gender.SelectedValue);
                    //Context.Profile.SetPropertyValue("ContactNo", contact.Text);
                    //Context.Profile.SetPropertyValue("PostalCode", postalCode.Text);
                }
            }
            catch (Exception)
            {

            }
            


        }

        protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
        {

            try
            {
                StructureFacade fac = new StructureFacade();


                drpBranch.Items.Clear();
                drpGroup.Items.Clear();
                drpUnit.Items.Clear();


                FillDropDown("Group");

                if (rdoUserTypes.SelectedIndex == 0)
                {//HQ
                    drpUnit.Enabled = false;
                    drpBranch.Enabled = false;
                    drpGroup.Enabled = false;
                }
                else if (rdoUserTypes.SelectedIndex == 1)
                {//Group

                    drpUnit.Enabled = false;
                    drpBranch.Enabled = false;
                    drpGroup.Enabled = true;
                }
                else if (rdoUserTypes.SelectedIndex == 2)
                {//Branch

                    drpGroup.Enabled = true;
                    drpBranch.Enabled = true;
                    drpUnit.Enabled = false;
                }
                else if (rdoUserTypes.SelectedIndex == 3)
                {//Unit

                    drpGroup.Enabled = true;
                    drpBranch.Enabled = true;
                    drpUnit.Enabled = true;
                }
            }
            catch (Exception)
            {
 
            }
            

        }

        protected void drpGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (rdoUserTypes.SelectedItem.Text == "Branch" || rdoUserTypes.SelectedItem.Text == "Unit")
                {
                    FillDropDown("Branch");
                }
            }
            catch (Exception)
            {

            }
           


        }

        protected void drpBranch_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (rdoUserTypes.SelectedItem.Text == "Unit")
                {
                    FillDropDown("Unit");
                }
            }
            catch (Exception)
            {

            }



        }


        public void FillDropDown(string type)
        {
            try
            {
                StructureFacade fac = new StructureFacade();

                string usrType = "EMPTY";

                if (!String.IsNullOrEmpty(Request.QueryString["x"]))
                {
                    usrType = Request.QueryString["x"].ToString();

                }

                int uType;
                switch (usrType)
                {
                    case "EMPTY":


                        switch (type)
                        {
                            case "Group":
                                List<SalesOneGroup> grp = fac.GetGroups("GroupId ASC");
                                SalesOneGroup grsel = new SalesOneGroup();
                                grsel.GroupId = -1;
                                grsel.Name = "Select";
                                grp.Insert(0, grsel);
                                drpGroup.DataSource = grp;
                                drpGroup.DataTextField = "Name";
                                drpGroup.DataValueField = "GroupId";
                                drpGroup.DataBind();
                                break;
                            case "Branch":
                                if (drpGroup.SelectedValue != "-1")
                                {
                                    List<Branch> br = fac.GetBranchesForGroup(Convert.ToInt32(drpGroup.SelectedValue));
                                    drpBranch.DataSource = br;
                                    Branch brSel = new Branch();
                                    brSel.BranchId = -1;
                                    brSel.BranchName = "Select";
                                    br.Insert(0, brSel);
                                    drpBranch.DataTextField = "BranchName";
                                    drpBranch.DataValueField = "BranchId";
                                    drpBranch.DataBind();
                                }
                                break;
                            case "Unit":
                                if (drpBranch.SelectedValue != "-1")
                                {
                                    List<SalesOneUnit> un = fac.GetUnitsInBranch(Convert.ToInt32(drpBranch.SelectedValue));
                                    SalesOneUnit unSel = new SalesOneUnit();
                                    unSel.UnitId = -1;
                                    unSel.Name = "Slect";
                                    un.Insert(0, unSel);
                                    drpUnit.DataSource = un;
                                    drpUnit.DataTextField = "Name";
                                    drpUnit.DataValueField = "UnitId";
                                    drpUnit.DataBind();
                                }
                                break;
                            default:
                                break;
                        }


                        break;
                    case "group":

                        drpBranch.Enabled = false;
                        drpUnit.Enabled = false;

                        if (Session["gr"] != null)
                        {
                            List<SalesOneGroup> grp = fac.GetGroups("GroupId ASC");
                            SalesOneGroup grsel = new SalesOneGroup();
                            grsel.GroupId = -1;
                            grsel.Name = "Select";
                            grp.Insert(0, grsel);
                            drpGroup.DataSource = grp;
                            drpGroup.DataTextField = "Name";
                            drpGroup.DataValueField = "GroupId";
                            drpGroup.DataBind();

                            int grpId = int.Parse(Session["gr"].ToString());
                            SalesOneGroup gr = fac.GetGroup(grpId);
                            drpGroup.SelectedValue = gr.GroupId.ToString();
                            drpGroup.Enabled = false;

                        }

                        break;
                    case "b":
                        drpUnit.Enabled = false;

                        if (Session["gr"] != null && Session["br"] != null)
                        {
                            List<SalesOneGroup> grp = fac.GetGroups("GroupId ASC");
                            SalesOneGroup grsel = new SalesOneGroup();
                            grsel.GroupId = -1;
                            grsel.Name = "Select";
                            grp.Insert(0, grsel);
                            drpGroup.DataSource = grp;
                            drpGroup.DataTextField = "Name";
                            drpGroup.DataValueField = "GroupId";
                            drpGroup.DataBind();

                            int grpId = int.Parse(Session["gr"].ToString());
                            SalesOneGroup gr = fac.GetGroup(grpId);
                            drpGroup.SelectedValue = gr.GroupId.ToString();
                            drpGroup.Enabled = false;

                            if (drpGroup.SelectedValue != "-1")
                            {
                                List<Branch> br = fac.GetBranchesForGroup(Convert.ToInt32(drpGroup.SelectedValue));
                                drpBranch.DataSource = br;
                                Branch brSel = new Branch();
                                brSel.BranchId = -1;
                                brSel.BranchName = "Select";
                                br.Insert(0, brSel);
                                drpBranch.DataTextField = "BranchName";
                                drpBranch.DataValueField = "BranchId";
                                drpBranch.DataBind();

                                int brId = int.Parse(Session["br"].ToString());
                                Branch brn = fac.GetBranch(brId);
                                drpBranch.SelectedValue = brn.BranchId.ToString();
                                drpBranch.Enabled = false;
                            }

                        }
                        break;
                    case "u":

                        if (Session["gr"] != null && Session["br"] != null && Session["un"] != null)
                        {
                            List<SalesOneGroup> grp = fac.GetGroups("GroupId ASC");
                            SalesOneGroup grsel = new SalesOneGroup();
                            grsel.GroupId = -1;
                            grsel.Name = "Select";
                            grp.Insert(0, grsel);
                            drpGroup.DataSource = grp;
                            drpGroup.DataTextField = "Name";
                            drpGroup.DataValueField = "GroupId";
                            drpGroup.DataBind();

                            int grpId = int.Parse(Session["gr"].ToString());
                            SalesOneGroup gr = fac.GetGroup(grpId);
                            drpGroup.SelectedValue = gr.GroupId.ToString();
                            drpGroup.Enabled = false;

                            if (drpGroup.SelectedValue != "-1")
                            {
                                List<Branch> br = fac.GetBranchesForGroup(Convert.ToInt32(drpGroup.SelectedValue));
                                drpBranch.DataSource = br;
                                Branch brSel = new Branch();
                                brSel.BranchId = -1;
                                brSel.BranchName = "Select";
                                br.Insert(0, brSel);
                                drpBranch.DataTextField = "BranchName";
                                drpBranch.DataValueField = "BranchId";
                                drpBranch.DataBind();

                                int brId = int.Parse(Session["br"].ToString());
                                Branch brn = fac.GetBranch(brId);
                                drpBranch.SelectedValue = brn.BranchId.ToString();
                                drpBranch.Enabled = false;
                            }

                            if (drpBranch.SelectedValue != "-1")
                            {
                                List<SalesOneUnit> un = fac.GetUnitsInBranch(Convert.ToInt32(drpBranch.SelectedValue));
                                SalesOneUnit unSel = new SalesOneUnit();
                                unSel.UnitId = -1;
                                unSel.Name = "Slect";
                                un.Insert(0, unSel);
                                drpUnit.DataSource = un;
                                drpUnit.DataTextField = "Name";
                                drpUnit.DataValueField = "UnitId";
                                drpUnit.DataBind();

                                int unId = int.Parse(Session["un"].ToString());
                                SalesOneUnit unx = fac.GetUnit(unId);
                                drpUnit.SelectedValue = unx.UnitId.ToString();
                                drpUnit.Enabled = false;
                            }

                        }

                        break;

                    case "HQ":
                        List<SalesOneGroup> grx = fac.GetGroups("GroupId ASC");
                        SalesOneGroup grselx = new SalesOneGroup();
                        grselx.GroupId = -1;
                        grselx.Name = "Select";
                        grx.Insert(0, grselx);
                        drpGroup.DataSource = grx;
                        drpGroup.DataTextField = "Name";
                        drpGroup.DataValueField = "GroupId";
                        drpGroup.DataBind();

                        drpUnit.Enabled = false;
                        drpBranch.Enabled = false;
                        drpGroup.Enabled = false;

                        break;
                    default:
                        break;
                }
            }
            catch (Exception)
            {

            }
            






            //switch (type)
            //{
            //    case "Group":
            //        List<SalesOneGroup> grp = fac.GetGroups("GroupId ASC");
            //        SalesOneGroup grsel = new SalesOneGroup();
            //        grsel.GroupId = -1;
            //        grsel.Name = "Select";
            //        grp.Insert(0, grsel);
            //        drpGroup.DataSource = grp;
            //        drpGroup.DataTextField = "Name";
            //        drpGroup.DataValueField = "GroupId";
            //        drpGroup.DataBind();
            //        break;
            //    case "Branch":
            //        if (drpGroup.SelectedValue != "-1")
            //        {
            //            List<Branch> br = fac.GetBranchesForGroup(Convert.ToInt32(drpGroup.SelectedValue));
            //            drpBranch.DataSource = br;
            //            Branch brSel = new Branch();
            //            brSel.BranchId = -1;
            //            brSel.BranchName = "Select";
            //            br.Insert(0, brSel);
            //            drpBranch.DataTextField = "BranchName";
            //            drpBranch.DataValueField = "BranchId";
            //            drpBranch.DataBind();
            //        }
            //        break;
            //    case "Unit":
            //        if (drpBranch.SelectedValue != "-1")
            //        {
            //            List<SalesOneUnit> un = fac.GetUnitsInBranch(Convert.ToInt32(drpBranch.SelectedValue));
            //            SalesOneUnit unSel = new SalesOneUnit();
            //            unSel.UnitId = -1;
            //            unSel.Name = "Slect";
            //            un.Insert(0, unSel);
            //            drpUnit.DataSource = un;
            //            drpUnit.DataTextField = "Name";
            //            drpUnit.DataValueField = "UnitId";
            //            drpUnit.DataBind();
            //        }
            //        break;
            //    default:
            //        break;
            //}
        }

        protected void drpBranch_Load(object sender, EventArgs e)
        {

        }

        protected void chkUserType_SelectedIndexChanged(object sender, EventArgs e)
        {

            try
            {
                StructureFacade fac = new StructureFacade();
                ArrayList ar = new ArrayList();



                foreach (ListItem it in chkUserType.Items)
                {
                    if (it.Selected)
                    {
                        //Guid grId = new Guid(chkRoles.Items[i].Value);
                        //UserRole role = fac.GetUserRole(grId);


                        ar.Add(Convert.ToInt32(it.Value));

                    }
                }

                List<UserRole_aspnet> rls = fac.GetAllRolesForUserTypes((int[])ar.ToArray(typeof(int)));
                List<UserRole_aspnet> rlx = new List<UserRole_aspnet>();


                foreach (UserRole_aspnet rl in rls)
                {
                    UserRole role = fac.GetUserRole(rl.RoleId);
                    if (role.Status == 1)
                    {
                        rlx.Add(rl);
                    }
                }

                chkRoles.DataSource = rlx;
                chkRoles.DataTextField = "RoleName";
                chkRoles.DataValueField = "RoleId";
                chkRoles.DataBind();
            }
            catch (Exception)
            {

            }
            

        }

        protected void wizCreateUser_FinishButtonClick(object sender, WizardNavigationEventArgs e)
        {
            try
            {
                if (chkRoles.Items.Count == 0)
                {
                    Session["uInSuc"] = "0";
                    Response.Redirect(ViewState["refUrl"].ToString(), false);
   

                }
                else
                {
                    string[] usrProps = (string[])Session["newUser"];

                    User user = new User();

                    MembershipUser adUser = Membership.GetUser(User.Identity.Name);
                    Guid adkey = (Guid)adUser.ProviderUserKey;

                    user.LastUpBy = adkey.ToString();

                    user.Name = usrProps[0];
                    if (usrProps[1] != "-1")
                    {
                        user.IdType = usrProps[1];
                    }

                    user.IdNo = usrProps[2];
                    user.Address1 = usrProps[3];
                    user.Address2 = usrProps[4];

                    if (usrProps[5] != "-1")
                    {
                        user.Country = usrProps[5];
                    }

                    user.City = usrProps[6];
                    user.Gender = usrProps[7];
                    user.Contact = usrProps[8];
                    user.PostalCode = usrProps[9];

                    //if (!string.IsNullOrEmpty(usrProps[9]))
                    //{
                    //    user.PostalCode = Convert.ToInt32(usrProps[9]);
                    //}

                    user.LastUpdateDate = DateTime.Now.ToShortDateString();


                    int k = 0;
                    foreach (ListItem chIt in chkRoles.Items)
                    {
                        if (chIt.Selected)
                        {
                            k++;
                        }
                    }

                    string[] roleName = new string[k];


                    int j = 0;
                    foreach (ListItem chItm in chkRoles.Items)
                    {
                        if (chItm.Selected)
                        {
                            roleName[j] = chItm.Text;
                            //chkRoles.Items[i].Text;
                            j++;
                        }
                    }

                    StructureFacade sFac = new StructureFacade();
                    int nodeId = 0;
                    int userType = 1;
                    int suc = 0;

                    if (rdoUserTypes.SelectedItem.Text == "Group" && drpGroup.SelectedValue != "-1")
                    {
                        nodeId = Convert.ToInt32(drpGroup.SelectedValue);
                        userType = 2;
                        //stFac.InsertToUserInStructure(userGuuids, userType, nodeId);
                    }
                    else if (rdoUserTypes.SelectedItem.Text == "Branch" && drpBranch.SelectedValue != "-1")
                    {
                        nodeId = Convert.ToInt32(drpBranch.SelectedValue);
                        userType = 3;
                        //stFac.InsertToUserInStructure(userGuuids, userType, nodeId);
                    }
                    else if (rdoUserTypes.SelectedItem.Text == "Unit" && drpUnit.SelectedValue != "-1")
                    {
                        nodeId = Convert.ToInt32(drpUnit.SelectedValue);
                        userType = 4;
                        //stFac.InsertToUserInStructure(userGuuids, userType, nodeId);
                    }
                    else if (rdoUserTypes.SelectedItem.Text == "HQ")
                    {
                        userType = 1;
                        //stFac.InsertToUserInStructure(userGuuids, userType, nodeId);
                    }
                    else
                    {
                        MassageSummery("IIS502");
                        suc = 1;
                    }


                    if (suc == 0)
                    {
                        sFac.AddUser(usrProps, user, roleName, userType, nodeId);
                        Session["uInSuc"] = "1";
                        Response.Redirect(ViewState["refUrl"].ToString(),false);
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("23"))
                {
                    Session["uInSuc"] = "23";
                }
                else if (ex.Message.Contains("24"))
                {
                    Session["uInSuc"] = "24";
                }
                else if (ex.Message.Contains("25"))
                {
                    Session["uInSuc"] = "25";
                }
                else if (ex.Message.Contains("26"))
                {
                    Session["uInSuc"] = "26";
                }
                else if (ex.Message.Contains("27"))
                {
                    Session["uInSuc"] = "27";
                }
                else if (ex.Message.Contains("28"))
                {
                    Session["uInSuc"] = "28";
                }
                else if (ex.Message.Contains("29"))
                {
                    Session["uInSuc"] = "29";
                }
                else if (ex.Message.Contains("30"))
                {
                    Session["uInSuc"] = "30";
                }
                else if (ex.Message.Contains("31"))
                {
                    Session["uInSuc"] = "31";
                }
                else if (ex.Message.Contains("32"))
                {
                    Session["uInSuc"] = "32";
                }
                else
                {
                    Session["uInSuc"] = "0";
                }


                Response.Redirect(ViewState["refUrl"].ToString(), false);


            }

        }

        protected void ContinueButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (!String.IsNullOrEmpty(Request.QueryString["a"]))
                {
                    action = Request.QueryString["a"].ToString();


                }

                if (action == "v")
                {
                    Response.Redirect(Request.UrlReferrer.ToString());
                }
                else
                {
                    TextBox name = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("txtName");
                    DropDownList idType = (DropDownList)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("drpIdType");
                    TextBox idNo = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("txtIdNo");
                    TextBox address1 = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("txtAddress1");
                    TextBox address2 = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("txtAddress2");
                    DropDownList country = (DropDownList)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("drpCountry");
                    TextBox city = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("txtCity");
                    DropDownList gender = (DropDownList)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("drpGender");
                    TextBox contact = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("txtContact");
                    TextBox postalCode = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("txtPostalCode");

                    TextBox userName = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("UserName");
                    TextBox intranetUserName = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("IntranetUserName");
                    TextBox passWord = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("Password");
                    TextBox eMail = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("Email");
                    TextBox question = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("Question");
                    TextBox answer = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("Answer");


                    string[] usrProps = { name.Text, idType.SelectedValue.ToString(), idNo.Text, address1.Text, address2.Text, country.Text, city.Text, gender.SelectedIndex.ToString(), contact.Text, postalCode.Text, userName.Text, passWord.Text, eMail.Text, question.Text, answer.Text, intranetUserName.Text };

                    MembershipUser us = Membership.GetUser(name.Text);
                    if (us == null)
                    {
                        if (!string.IsNullOrEmpty(contact.Text) && contact.Text.Length > 15)
                        {
                            MassageSummery("IIS538");
                            wizCreateUser.ActiveStepIndex = 0;
                        }
                        else if (country.SelectedItem.Text == "Select")
                        {
                            MassageSummery("IIS501");
                        }
                        else if (idType.SelectedItem.Text == "Select")
                        {
                            MassageSummery("IIS501");
                            //FailureText.Text = FailureText.Text + " Please put a valid value for Country ";
                        }
                        else
                        {
                            Session["newUser"] = usrProps;
                            wizCreateUser.ActiveStepIndex = 1;
                            Response.Redirect(ViewState["refUrl"].ToString());
                        }

                    }
                    else
                    {//error
                        MassageSummery("IIS521");
                        wizCreateUser.ActiveStepIndex = 0;

                    }


                }
            }
            catch (Exception)
            {

            }
             
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                Response.Redirect(ViewState["refUrl"].ToString());
            }
            catch (Exception)
            {
            }
            
        }

        protected void lbtnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                Response.Redirect(ViewState["refUrl"].ToString());
            }
            catch (Exception)
            {

            }

        }

        protected void chkRoles_SelectedIndexChanged(object sender, EventArgs e)
        {

        }


        protected void CreateNewUser()
        { 
        
        
        
        }


        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(Request.QueryString["a"]))
            {
                action = Request.QueryString["a"].ToString();


            }

            if (action == "v")
            {
                Response.Redirect(Request.UrlReferrer.ToString());
            }
            else
            {
                TextBox name = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("txtName");
                DropDownList idType = (DropDownList)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("drpIdType");
                TextBox idNo = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("txtIdNo");
                TextBox address1 = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("txtAddress1");
                TextBox address2 = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("txtAddress2");
                DropDownList country = (DropDownList)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("drpCountry");
                TextBox city = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("txtCity");
                DropDownList gender = (DropDownList)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("drpGender");
                TextBox contact = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("txtContact");
                TextBox postalCode = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("txtPostalCode");

                TextBox userName = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("UserName");
                TextBox intranetUserName = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("IntranetUserName");
                TextBox passWord = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("Password");
                TextBox eMail = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("Email");
                TextBox question = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("Question");
                TextBox answer = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("Answer");


                string[] usrProps = { name.Text, idType.SelectedValue.ToString(), idNo.Text, address1.Text, address2.Text, country.Text, city.Text, gender.SelectedIndex.ToString(), contact.Text, postalCode.Text, userName.Text, passWord.Text, eMail.Text, question.Text, answer.Text, intranetUserName.Text };

                MembershipUser us = Membership.GetUser(name.Text);
                if (us == null)
                {
                    Session["newUser"] = usrProps;
                    wizCreateUser.ActiveStepIndex = 1;
                }
                else
                {//error

                }

                


                

            }
        }

        protected void btnNext_Click(object sender, EventArgs e)
        {
            try
            {
                if (!String.IsNullOrEmpty(Request.QueryString["a"]))
                {
                    action = Request.QueryString["a"].ToString();


                }

                if (action == "v")
                {
                    Response.Redirect(Request.UrlReferrer.ToString());
                }
                else
                {
                    TextBox name = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("txtName");
                    DropDownList idType = (DropDownList)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("drpIdType");
                    TextBox idNo = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("txtIdNo");
                    TextBox address1 = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("txtAddress1");
                    TextBox address2 = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("txtAddress2");
                    DropDownList country = (DropDownList)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("drpCountry");
                    TextBox city = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("txtCity");
                    DropDownList gender = (DropDownList)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("drpGender");
                    TextBox contact = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("txtContact");
                    TextBox postalCode = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("txtPostalCode");

                    TextBox userName = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("UserName");
                    TextBox intranetuserName = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("IntranetUserName");
                    TextBox passWord = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("Password");
                    TextBox eMail = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("Email");
                    //TextBox question = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("Question");
                    //TextBox answer = (TextBox)wizCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("Answer");


                    string[] usrProps = { name.Text, idType.SelectedValue.ToString(), idNo.Text, address1.Text, address2.Text, country.Text, city.Text, gender.SelectedIndex.ToString(), contact.Text, postalCode.Text, userName.Text, passWord.Text, eMail.Text, intranetuserName.Text};

                    MembershipUser us = Membership.GetUser(name.Text);
                    if (us == null)
                    {
                        if (!string.IsNullOrEmpty(contact.Text) && contact.Text.Length > 15)
                        {
                            MassageSummery("IIS520");
                            wizCreateUser.ActiveStepIndex = 0;
                        }
                        else if (country.SelectedItem.Text == "Select")
                        {
                            MassageSummery("IIS501");
                        }
                        else if (idType.SelectedItem.Text == "Select")
                        {
                            MassageSummery("IIS501");
                            //FailureText.Text = FailureText.Text + " Please put a valid value for Country ";
                        }
                        else if (passWord.Text.Length <= 6)
                        {
                            MassageSummery("IIS520");
                        }
                        else if (CheckIntranetUsernameExistance(intranetuserName.Text.Trim().ToLower()))
                        {
                            MassageSummery("IIS546");
                        }
                        else
                        {
                            Session["newUser"] = usrProps;
                            wizCreateUser.ActiveStepIndex = 1;
                        }
                    }
                    else
                    {//error
                        MassageSummery("IIS521");
                        wizCreateUser.ActiveStepIndex = 0;
                    }
                }
            }
            catch (Exception)
            {
            }
        }

        /// <summary>
        /// Suren Manawatta
        /// 2012-10-31
        /// Check the existance of the intranet username in aspnetUser table
        /// </summary>
        /// <param name="usrName">Intranet username which need to check</param>
        /// <returns>False - If username not exist</returns>
        private bool CheckIntranetUsernameExistance(string usrName)
        {
            try
            {
                using (SODataDataContext db = DataContextFactory.CreateContext())
                {
                    var extUser = db.aspnet_Users.SingleOrDefault(p => p.IntranetUN.Equals(usrName));
                    if (extUser == null)
                    {
                        return false;
                    }
                    return true;
                }
            }
            catch (Exception)
            {
                return true;
            }
        }

        protected void btnCancel_Click1(object sender, EventArgs e)
        {
            Response.Redirect(ViewState["refUrl"].ToString());
        }

        protected void ContinueButton_Click1(object sender, EventArgs e)
        {

        }
    }
}
